﻿namespace MyCoreLib.Automation.Data.SqlClient.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Metadata;

    public class EnvironmentSettingsReader : IEnvironmentSettingsReader
    {
        private readonly IOutput Output;

        public EnvironmentSettingsReader(IOutput output)
        {
            if (ReferenceEquals(output, null))
            {
                throw new ArgumentNullException("output");
            }
            Output = output;
        }

        public string GetConnectionString(
            string defaultConnectionString,
            IEnumerable<IEnvironmentSettings> environmentSettings)
        {
            if (ReferenceEquals(environmentSettings, null) == false)
            {
                var envConnectionStrings = (from s in environmentSettings
                                            where ReferenceEquals(s, null) == false
                                            where s.MachineName.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase)
                                            select s.ConnectionString).Distinct().ToList();
                if (envConnectionStrings.Count == 1)
                {
                    if (String.IsNullOrWhiteSpace(envConnectionStrings[0]))
                    {
                        Output.Warning("The {0} environment connection string is not specified.", Environment.MachineName);
                    }
                    else
                    {
                        return envConnectionStrings[0];
                    }
                }
                else if (envConnectionStrings.Count > 0)
                {
                    Output.Error(new StringBuilder()
                        .AppendFormat("There are multiple connection strings specified for the {0} environment.", Environment.MachineName)
                        .Append(" Ensure that a single connection string is specified for this environment."));
                }
            }

            if (String.IsNullOrWhiteSpace(defaultConnectionString))
            {
                Output.Error("Neither default connection string, no environment specific one is specified.");
                throw new ProcessingStoppedException();
            }
            return defaultConnectionString;
        }


        public async Task<HashSet<string>> GetAllProcedureNamesAsync(ISqlSchemaReader reader, CancellationToken token)
        {
            var fullNames = await reader.LoadStoredProcedureFullNamesAsync(token);
            return new HashSet<string>(fullNames, StringComparer.OrdinalIgnoreCase);
        }
    }
}
